<template>
  <div class="container">
    <el-form :model="form" label-width="auto" style="max-width: 600px" :inline="true">
      <el-form-item label="请选择常数类别">
        <el-select
          @change="typeChange"
          v-model="selectType"
          placeholder="请选择常数类别..."
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="toAdd">添加</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-table :data="tableData.list" style="width: 100%" >
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="constantTypeId" label="类别ID" width="100"/>
        <el-table-column prop="code" label="常数项编码" width="180"/>
        <el-table-column prop="name" label="常数项名称" width="180"/>
        <el-table-column label="状态" width="100">
  <template #default="{row}">
    <el-tag :type="row.isDeleted === 1 ? 'success' : 'danger'">
      {{ row.isDeleted === 1 ? '已启用' : '已禁用' }}
    </el-tag>
  </template>
</el-table-column>
        <el-table-column label="操作" width="180">
  <template #default="scope">
    <el-button link type="primary" size="small" @click="toEdit(scope.row)">编辑</el-button>
    <el-button 
      link 
      type="primary" 
      size="small"
      @click="toggleStatus(scope.row)"
    >
      {{ scope.row.isDeleted === 1 ? '禁用' : '启用' }}
    </el-button>
    <el-button 
      link 
      type="danger" 
      size="small"
      @click="deleteItem(scope.row)"
    >
      删除
    </el-button>
  </template>
</el-table-column>
      </el-table>
      <el-pagination
      background
      layout="prev, pager, next, total"
      :total="tableData.total"
      :page-size="10"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    </div>

    <el-dialog 
      v-model="editDialogFormVisible" 
      :title="editForm.id ? '编辑常数项' : '添加常数项'" 
      width="500"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="常数类别ID" prop="constantTypeId">
          <el-input v-model="editForm.constantTypeId" disabled v-if="editForm.id"/>
          <el-select 
            v-model="editForm.constantTypeId" 
            placeholder="请选择常数类别"
            v-else
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="常数项编码" prop="code">
          <el-input v-model="editForm.code"/>
        </el-form-item>
        <el-form-item label="常数项名称" prop="name">
          <el-input v-model="editForm.name"/>
        </el-form-item>
        <el-form-item label="状态" prop="isDeleted" v-if="editForm.id">
          <el-radio-group v-model="editForm.isDeleted">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="editDialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
const currentPage = ref(1)
const tableData = ref({
  list: [],
  total: 0
})
const selectType = ref('')
const options = ref([])
const form = ref({})
const editDialogFormVisible = ref(false)
const loading = ref(false)

// 编辑表单数据
const editForm = ref({
  id: null,
  constantTypeId: '',
  code: '',
  name: '',
  isDeleted: 1
})

// 获取常数项列表
async function getConstantItems() {
  try {
    loading.value = true
    const response = await service.get("/constantItem/list", {
      params: {
        pageNum: currentPage.value,
        pageSize: 10 // 固定每页10条
      }
    })
    // 直接使用已解析的PageInfo对象
    tableData.value = {
      list: response?.list || [], // 直接使用response
      total: response?.total || 0
    };
  } catch (error) {
    ElMessage.error('获取数据失败');
    tableData.value = { list: [], total: 0 };
  } finally {
    loading.value = false;
  }
}



// 分页事件处理
const handlePageChange = (val) => {
  currentPage.value = val
  if (selectType.value) {
    getByTypeId(selectType.value)
  } else {
    getConstantItems()
  }
}


// 根据类型获取常数项
async function getByTypeId(typeId) {
  try {
    loading.value = true;
    const response = await service.get("/constantItem/select", {
      params: {
        constantTypeId: typeId,
        pageNum: currentPage.value,
        pageSize: 10
      }
    });
    
   // 直接使用已解析的PageInfo对象
   tableData.value = {
      list: response?.list || [], // 直接使用response
      total: response?.total || 0
    };
    
  } catch (error) {
    ElMessage.error('获取分类数据失败');
    tableData.value = { list: [], total: 0 };
  } finally {
    loading.value = false;
  }
}
// 类别选择变化
function typeChange(typeId) {
  if (typeId) {
    getByTypeId(typeId)
  } else {
    getConstantItems()
  }
}

// 添加按钮
function toAdd() {
  if (!selectType.value) {
    ElMessage.warning('请先选择常数类别');
    return;
  }
  
  editForm.value = {
    id: null,
    constantTypeId: selectType.value, // 确保包含类别ID
    code: '',
    name: '',
    isDeleted: 1 // 默认启用状态
  };
  editDialogFormVisible.value = true;
}

// 编辑按钮
function toEdit(row) {
  editForm.value = { ...row }
  editDialogFormVisible.value = true
}

// 切换状态
// 切换状态
async function toggleStatus(row) {
  try {
    await ElMessageBox.confirm(
      `确认要${row.isDeleted === 1 ? '禁用' : '启用'}该条目吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用更新接口来切换状态
    const newStatus = row.isDeleted === 1 ? 0 : 1
    await service.patch("/constantItem/update/", {
      ...row,
      isDeleted: newStatus
    })
    
    ElMessage.success('状态更新成功')
    typeChange(selectType.value)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
      console.error('Error updating status:', error)
    }
  }
}

// 保存数据
async function save() {
  try {
    if (!editForm.value.constantTypeId || !editForm.value.code || !editForm.value.name) {
      ElMessage.error('请填写完整信息')
      return
    }

    if (editForm.value.id) {
      // Update existing item
      const response = await service.patch("/constantItem/update/", {
        id: editForm.value.id,
        constantTypeId: editForm.value.constantTypeId,
        code: editForm.value.code,
        name: editForm.value.name,
        isDeleted: editForm.value.isDeleted
      })
      if (response) {
        ElNotification.success({
          title: '成功',
          message: '更新成功'
        })
      }
    } else {
      // Add new item
      const response = await service.post("/constantItem/add", {
        constantTypeId: editForm.value.constantTypeId,
        code: editForm.value.code,
        name: editForm.value.name,
        isDeleted: 1 // 默认启用状态
      })
      if (response) {
        ElNotification.success({
          title: '成功',
          message: '添加成功'
        })
      }
    }
    
    editDialogFormVisible.value = false
    typeChange(selectType.value)
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
    console.error('Error saving data:', error)
  }
}
//删除
async function deleteItem(row) {
  try {
    await ElMessageBox.confirm(
      '确认要删除该条目吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 根据后端接口，需要传递一个包含id的对象
    await service.delete("/constantItem/delete", {
      data: {
        id: row.id
      }
    })
    
    ElMessage.success('删除成功')
    typeChange(selectType.value)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Error deleting item:', error)
    }
  }
}

// 初始化加载数据
onMounted(async () => {
  try {
    // 加载常数类别列表
    const typeResponse = await service.get("/constantType/list")
    // 处理可能的响应数据结构
    options.value = Array.isArray(typeResponse) 
      ? typeResponse 
      : (Array.isArray(typeResponse.data) 
        ? typeResponse.data 
        : (Array.isArray(typeResponse.list) ? typeResponse.list : []))
    
    // 默认加载第一类别的数据
    if (options.value.length > 0) {
      selectType.value = options.value[0].id
      await getByTypeId(selectType.value)
    } else {
      await getConstantItems()
    }
  } catch (error) {
    ElMessage.error('初始化数据失败: ' + (error.message || '未知错误'))
    console.error('Init Error:', error)
    options.value = []
    tableData.value = { list: [], total: 0 }
  }
})
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>